package com.example.demo.filter;

import com.example.demo.handler.MyAuthenticationFailureHandler;
import com.example.demo.handler.MyAuthenticationSuccessHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.IOException;
import java.util.Map;

public class JsonAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            // 从请求中获取JSON数据
            Map map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
            // 获取用户名
            String username = (String) map.get("username");
            // 获取密码
            String password = (String) map.get("password");
            // 创建一个用户名密码认证令牌
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            // 设置认证令牌的详细信息
            setDetails(request, authenticationToken);
            // 使用认证管理器进行认证
            return this.getAuthenticationManager().authenticate(authenticationToken);
        } catch (IOException e) {
            // 抛出运行时异常
            throw new RuntimeException("Json解析失败", e);
        }
    }

    public JsonAuthenticationFilter(StringRedisTemplate stringRedisTemplate, AuthenticationManager authenticationManager) {
        super.setFilterProcessesUrl("/user/login");
        super.setAuthenticationSuccessHandler(new MyAuthenticationSuccessHandler(stringRedisTemplate));
        super.setAuthenticationFailureHandler(new MyAuthenticationFailureHandler());
        super.setAuthenticationManager(authenticationManager);
        System.out.println("AuthenticationManager: " + (super.getAuthenticationManager() != null));
    }
}
